package com.nebula.tcp.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

public class NebulaNettyChannelInitializer<SocketChannel> extends ChannelInitializer<Channel> {



    private static final int READ_IDEL_TIME_OUT = 660; // 读超时，单位是秒，为:11分钟检测一次是否超时
    private static final int WRITE_IDEL_TIME_OUT = 0;// 写超时
    private static final int ALL_IDEL_TIME_OUT = 0; // 所有超时


    @Override
    protected void initChannel(Channel ch) throws Exception {

        //半包/拆包/粘包数据处理
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(1, 1);
        buffer.writeByte('#');
        //设置包的字节长度，数据超过2048个字节则服务端不会收到。
        ch.pipeline().addLast(new DelimiterBasedFrameDecoder(2048,buffer));

        // ChannelOutboundHandler，依照逆序执行
        ch.pipeline().addLast("encoder", new StringEncoder());

        // 属于ChannelInboundHandler，依照顺序执行
        ch.pipeline().addLast("decoder", new StringDecoder());

        //设置超时时间，多久没有收到消息，则认为是断开连接状态
        ch.pipeline().addLast(new IdleStateHandler(READ_IDEL_TIME_OUT,WRITE_IDEL_TIME_OUT,ALL_IDEL_TIME_OUT));
        /**
         * 自定义ChannelInboundHandlerAdapter
         */
        ch.pipeline().addLast(new NebulaNettyChannelInAdapter());
    }

}
